function ReplaceAll(Source,stringToFind,stringToReplace){
  var temp = Source;
    var index = temp.indexOf(stringToFind);
        while(index != -1){
            temp = temp.replace(stringToFind,stringToReplace);
            index = temp.indexOf(stringToFind);
        }
        return temp;
}

function upload(BtnUpload , Status, SubmitVar, contentId,base_url ){
        var time = (new Date).getTime();
        new AjaxUpload((BtnUpload), {
            action: '?r=imageUpload',
            name: SubmitVar,
            data: {
                r: 'imageUpload',
                timestamp: time, 
            },
            responseType: false,
            onSubmit: function(file, ext){
                 if (! (ext && /^(jpg|png|jpeg|bmp)$/.test(ext))){ 
                    alert("Chi cho phép file jpg, png");
                                      
                }
                
                Status.text('Đang tải ... ');
            },
            onComplete: function(file, response){
                //On completion clear the status
                Status.text('');
                //Add uploaded file to list
                   var temp_src = base_url+time+'-'+file;
                   var src = ReplaceAll(temp_src,' ','');
                   alert(src);
                   contentId.removeAttr('src');
                   contentId.attr({'src':src});
                   return false;
            }
        });
    }
    
    function uploadWithoutDisplay(BtnUpload, SubmitVar, contentId ){
        var time = (new Date).getTime();
        new AjaxUpload((BtnUpload), {
            action: '?r=upload/default/index',
            name: SubmitVar,
            data: {
                r: 'upload/default/index',
                timestamp: time,
            },
            responseType: false,
            onSubmit: function(file, ext){
                 if (! (ext && /^(jpg|png|jpeg|bmp)$/.test(ext))){ 
                    alert("Chi cho phép file jpg, png");
                }
            },
            onComplete: function(file, response){
                if(response == 'success'){
                    var temp_src = base_url+time+'-'+file;
                    var src = ReplaceAll(temp_src,' ','');
                   $("#"+contentId).val(src);
                   alert("Upload image "+file+ "success! Image URL ="+src);
                   //contentId.removeAttr('src');
                   //contentId.attr({'src':src});
                   //return false;
                }else{
                    alert('Upload fail');
                }
            }
        });
    }

$(document).ready(function(){
   $("#save").click(function(){
      document.getElementById("create_form").submit(); 
   });

    uploadWithoutDisplay( $("#thumb"), 'icon', $("#thumb") );
   uploadWithoutDisplay( $("#icon"), 'icon', $("#icon_url") );
   
});